package com.demo.mall.wap.controller;

import com.demo.goods.client.service.GoodsRestService;
import com.demo.goods.client.util.TreeMapConvert;
import com.demo.goods.object.GoodsQo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsRestService goodsRestService;


    @RequestMapping(value="/index")
    public ModelAndView index(ModelMap model, HttpServletRequest request) throws Exception{
        String sortsid = request.getParameter("sortsid");
        return new ModelAndView("goods/index", "sortsid", sortsid);
    }


    @RequestMapping(value="/{id}")
    public ModelAndView findById(@PathVariable Long id) {
        String json = goodsRestService.findById(id);
        GoodsQo goodsQo = new Gson().fromJson(json, GoodsQo.class);
        return new ModelAndView("goods/show", "goods", goodsQo);
    }


    @RequestMapping(value = "/list")
    public Page<Map<String, Object>> findAll(GoodsQo goodsQo) {
        String json = goodsRestService.findPage(goodsQo);

        Gson gson = TreeMapConvert.getGson();
        TreeMap<String,Object> page = gson.fromJson(json, new TypeToken< TreeMap<String,Object>>(){}.getType());

        Pageable pageable = PageRequest.of(goodsQo.getPage(), goodsQo.getSize(), null);
        List<GoodsQo> list = new ArrayList<>();

        if(page != null && page.get("content") != null) {
            list = gson.fromJson(page.get("content").toString(), new TypeToken<List<GoodsQo>>() {
            }.getType());
        }
        String count = page.get("totalelements").toString();

        return new PageImpl(list, pageable, new Long(count));
    }

}
